<template>
<q-dialog class="cloud-file-dialog dialog" v-model="show" persistent>
  <q-card v-drag style="min-width: 560px" class="no-shadow dialog-content">
    <q-card-section class="dialog-title bg-primary">
      <div class="text-center text-white">
        从我的空间选择
      </div>
    </q-card-section>
    <div class="content relative-position">
      <q-tabs
        v-model="tab"
        shrink stretch dense
        inline-label
        align="left"
        active-color="primary"
        indicator-color="primary"
        @input="getInfoList"
      >
        <q-tab name="all" label="全部文件" />
        <q-tab name="lastUse" label="最近使用" />
      </q-tabs>
      <!--      返回-->
      <q-btn v-show="tab==='all'" @click="back" class="back-btn"
             flat round dense size="sm"
             icon="iconfont icontubiao-58" />

      <div class="relative-position" @click="clearActFile()">
        <q-scroll-area
          :thumb-style="CommonConfig.thumbStyle"
          style="height: 210px"
          class="bg-white scorll-content"
        >
          <div class="file-list full-height">
            <file-item v-for="(file, fileIndex) in files" :key="fileIndex"
                       :file="file" :file-index="fileIndex"
                       :is-active="isActDay(file)" :is-show-menu="false"
                       @selFiles="setFile" @dblclickE="dblclickE"
            />
          </div>
        </q-scroll-area>
        <q-inner-loading :showing="fileLoading">
          <q-spinner-gears size="50px" color="primary" />
        </q-inner-loading>
      </div>
    </div>
    <!--    底部确认取消-->
    <q-card-section class="dialog-footer text-center margin-t-10 margin-b-10 no-padding">
      <q-btn class="btn q-mr-md" outline label="取消" color="primary" @click="hideDialog" />
      <q-btn class="btn" unelevated label="确认" color="primary" @click="submit" />
    </q-card-section>
  </q-card>
</q-dialog>
</template>

<script>
import FileItem from './file-item'
import { getCloudList, getLastUseList } from 'src/boot/program/G-gov'
import { getFiletype } from 'src/assets/js/util'
export default {
  name: 'cloud-file-dialog',
  data () {
    return {
      show: false, // 控制弹框显示
      curDir: {}, // 所在位置
      tab: 'all', // 选中的tab值，all or lastUse
      files: [], // 文件列表数据
      actFile: [],
      clickTime: null, // 区分单击与双击
      fileLoading: false, // 文件数据加载
      curDirPath: null, // 当前选中的目录路径
      machinePosition: '' // 发送给机床的什么位置，cnc or box
    }
  },
  methods: {
    showDialog (machinePosition) {
      this.show = true
      this.machinePosition = machinePosition
      this.clearData()
      this.getInfoList()
    },
    hideDialog () {
      this.show = false
    },
    clearData () {
      this.curDir = {}
      this.tab = 'all'
      this.actFile = []
      this.curDirPath = null
    },
    // 获取文件列表,选择tab
    getInfoList () {
      if (this.tab === 'all') {
        this.getAll()
      } else {
        this.getLastUse()
      }
    },
    // 获取全部文件
    getAll (path = '') {
      this.fileLoading = true
      getCloudList(path).then((res) => {
        let dirs = this.initInfo(res.data.dirs, false)
        let files = this.initInfo(res.data.files, true, res.data.dirs.length)
        this.files = [].concat(dirs, files)
        this.total = this.files.length
        this.curDir = {
          ...res.data.curDir,
          source: 'cloud'
        }
      }).finally(() => {
        this.fileLoading = false
      })
    },
    // 获取最近使用数据
    getLastUse () {
      this.fileLoading = true
      getLastUseList().then((res) => {
        this.files = this.initInfo(res.data, true)
      }).finally(() => {
        this.fileLoading = false
      })
    },
    /**
     * 给数据添加必要的属性
     * @param info
     * @param isFile 是否是文件
     * @returns 新数据
     */
    initInfo (info, isFile, dirLength = 0) {
      let data = info.map((item, index) => {
        let type = isFile ? getFiletype(item.label) : 'other'
        let id = isFile ? index + 1 + dirLength : index + 1
        return {
          ...item,
          id,
          _name: item.label,
          isFile: isFile,
          type,
          source: 'cloud',
          icon: isFile ? 'img:statics/svg/' + type + '.svg' : 'img:statics/svg/file-icon.svg',
          children: []
        }
      })
      return data
    },

    // 是否是选中状态
    isActDay (file) {
      const index = this.actFile.findIndex(item => {
        return item.id === file.id
      })
      return index > -1
    },
    // 清空选中文件列表
    clearActFile (event) {
      console.log('clearActFile')
      this.actFile = []
    },
    // 返回
    back () {
      let pathArr = this.curDir.path.split('/')
      pathArr.pop()
      pathArr.pop()
      let path
      if (pathArr.length > 1) {
        path = pathArr.join('/') + '/'
      } else {
        path = ''
      }
      this.getAll(path)
    },
    // 单击选择文件，支持ctrl和shift多选
    setFile (e, item) {
      if (!item.isFile) return
      clearTimeout(this.clickTime)
      this.clickTime = setTimeout(() => {
        if (e.ctrlKey) {
          // 按住ctrl键
          const index = this.actFile.findIndex(file => {
            return file.id === item.id
          })
          if (index > -1) {
            this.actFile = this.actFile.filter(file => {
              return file.id !== item.id
            })
          } else {
            this.actFile.push(item)
          }
        } else if (e.shiftKey) {
          // 按住shift键
          if (this.actFile.length === 0) {
            this.actFile.push(item)
          } else {
            const maxIndex = this.getMaxIndex()
            const index = this.files.findIndex(file => {
              return file.id === item.id
            })
            let actFile = this.files.filter((file, fileIndex) => {
              const condition = (index > maxIndex && fileIndex <= index && fileIndex >= maxIndex) ||
                (index < maxIndex && fileIndex >= index && fileIndex <= maxIndex) ||
                (index === maxIndex && fileIndex === index)
              return condition
            })
            this.actFile = actFile
          }
        } else {
          // 单选
          const index = this.actFile.findIndex(file => {
            return file.id === item.id
          })
          this.actFile = index > -1 ? [] : [item]
        }
      }, 250)
    },
    // 获取存储在选中的file里面的最大最小角标
    getMaxIndex () {
      const indexArr = []
      this.actFile.forEach(item => {
        const index = this.files.findIndex(file => {
          return file.id === item.id
        })
        if (index > -1) {
          indexArr.push(index)
        }
      })
      indexArr.sort((a, b) => a > b ? 1 : -1)
      return indexArr[indexArr.length - 1]
    },
    // 双击文件夹进入
    dblclickE (file) {
      clearTimeout(this.clickTime)
      if (!file.isFile) {
        this.actFile = []
        this.curDir = file
        this.getAll(file.path)
      }
    },
    // 提交
    submit () {
      this.$emit('submit', this.actFile, this.machinePosition)
      this.hideDialog()
    }
  },
  components: {
    FileItem
  }
}
</script>

<style scoped lang="stylus">
.content{
  padding 5px 10px 20px
  border-top 1px solid #d3d3d3
  border-bottom 1px solid #d3d3d3
  >>>.q-tabs__content--align-justify .q-tab{
    flex 0 0 auto
  }
  .scorll-content{
    border 1px solid #d3d3d3
    border-radius 6px
  }
  .file-list{
    padding 10px 5px
    display flex
    flex-wrap wrap
  }
  .back-btn{
    position absolute
    top 12px
    right 20px
  }
}
</style>
